/**
 * Created by lvliqi on 2017/6/2.
 */
const router = require('koa-router')();
const Q = require('q');
const multiparty = require('multiparty');
const fs = require('fs');
const path = require('path');

const UPLOAD_TYPE_LOCAL = 1;
const UPLOAD_TYPE_CDN = 2;

router.post('/upload/local', async ctx => {
    let d = await receiveFile(ctx.req);

    let files = await fileGenerrateUrl({
        type: UPLOAD_TYPE_LOCAL,
        files: d
    });
    ctx.success(files);
});


let receiveFile = async (req) => {
    let defer = Q.defer();

    let form = new multiparty.Form();
    form.parse(req, function (err, fields, files) {
        if (err) {
            throw err;
        } else {
            let f = [];
            Object.keys(files).forEach(d => f = [...f, ...files[d]]);
            defer.resolve(f);
        }
    });

    return defer.promise;
};

let fileGenerrateUrl = async options => {
    let {type} = options;
    switch (type) {
        case UPLOAD_TYPE_LOCAL:
            return await fileGenerrateUrlLocal(options);
            break;
        case UPLOAD_TYPE_CDN:
            return await fileGenerrateUrlCdn(options);
            break;
        default:
            return null;
    }
};

let fileGenerrateUrlLocal = async options => {
    let {files, dir = path.join(process.cwd(), 'public/upload'), hostname = ''} = options;
    let p = '/upload';
    return files.map(d => {
        let filename = path.basename(d.path);
        let newDir = path.join(dir, filename);
        fs.renameSync(d.path, newDir);
        return {
            dir: newDir,
            path: `${p}/${filename}`,
            url: path.join(hostname, p, filename)
        }
    });
};

let fileGenerrateUrlCdn = async options => {

};

module.exports = router;
